<template>
  <div class="main">
    <div class="main-headerWrp">
      <div class="main-header clearfix">
        <div class="logo fl">
          <img class="logo__img" src="~@/assets/images/logo.jpg"/>
          <span class="logo__wrd">微智汇 · 控制台</span>
        </div>
        <div class="fl">
          <span class="hLink--active">总览</span>
          <router-link class="hLink" :to="{ name: 'create' }">接入小程序</router-link>
          <router-link v-if="userType ==='AGENCY' || userType === 'ADMIN'" class="hLink" :to="{ name: 'agency'}">代理后台</router-link>
        </div>
        <a href="javascript:void(0);" @click="loginOut" class="text-link fr">
          退出
        </a>
      </div>
    </div>
    <div class="main-conwrp">
      <div class="main-side">
        <div class="avatar">
          <img class="avatar__img" src="~@/assets/images/default-avatar.jpg"/>
          <div class="avatar__editBg">
            <span class="avatar__edit">更换</span>
          </div>
        </div>
        <div class="user-namewrp">
          <span class="user-name">
            {{userMobile}}
          </span>
        </div>
        <div class="user-info">
          <h4 class="user-info__mod">账号信息</h4>
          <div class="user-info__item clearfix">
            <span class="fl" style="color: #666;">管理员：</span>
            <span class="user-info__btn fr">
              <em class="text-primary">{{userName}}</em>
              &nbsp;&nbsp;
              <el-button type="text" @click="nameFormVisible = true">修改</el-button>
            </span>
          </div>
          <el-dialog title="管理员名称修改"  width="30%" :visible.sync="nameFormVisible">
            <el-form :model="nameForm"  :rules="nameFormRule" ref="nameForm">
              <el-form-item label="管理员名称" prop="name">
                <el-input v-model="nameForm.name" auto-complete="off"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="nameFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="updateUserName()">确 定</el-button>
            </div>
          </el-dialog>

          <div class="user-info__item clearfix">
            <span class="fl" style="color: #666;">密码：</span>
            <span class="user-info__btn fr">
              <em class="text-primary">******</em>
              &nbsp;&nbsp;
              <el-button type="text" @click="passwordFormVisible = true">修改</el-button>
            </span>
          </div>
           <el-dialog title="管理员密码修改"  width="30%" :visible.sync="passwordFormVisible">
            <el-form :model="passwordForm" :rules="passwordFormRule" ref="passwordForm"  >
              <el-form-item label="旧密码" prop="oldPassword">
                <el-input v-model="passwordForm.oldPassword" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="passwordForm.newPassword" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="请重新输入新密码" prop="secNewPassword">
                <el-input v-model="passwordForm.secNewPassword" auto-complete="off"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="passwordFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="updatePassword()">确 定</el-button>
            </div>
          </el-dialog>
        </div>
      </div>
      <div class="main-content">
        <el-carousel height="250px">
          <el-carousel-item v-for="item in 2" :key="item">
            <img src="https://venice-test-bucket.oss-cn-beijing.aliyuncs.com/images/sapp2.png">
          </el-carousel-item>
        </el-carousel>
        <div class="clearfix" style="margin: 20px 0;">
          <span>我的小程序</span>
          <div style="width: 60%;" class="fr">
            <el-input size="small" placeholder="小程序名称" v-model="appListForm.keyword" class="input-with-select">
              <el-select style="width: 120px;" @change="getDataList" v-model="appListForm.kind" slot="prepend" placeholder="所有店铺">
                <el-option label="所有店铺" value=""></el-option>
                <template v-for="(option,index) in appListForm.selects">
                  <el-option :key="index" :label="option.name" :value="option.id"></el-option>
                </template>
              </el-select>
              <el-button @click="getDataList" slot="append" icon="el-icon-search"></el-button>
            </el-input>

          </div>
        </div>
        <div class="app-list"  > 
          <el-row :gutter="20" v-loading="dataListLoading">
            <el-col :key="index" v-for="(item,index) in appList" :span="8">
              <div class="app-item">
                <p class="app-item__header">{{item.name}}</p>
                <div class="app-item__content">
                  <p>应用：<em class="text-primary">{{item.productName}}</em>/套餐：<em class="text-primary">{{item.priceType}}</em></p>
                  <p>状态：<em class="text-primary">{{item.status.desc}}</em></p>
                  <p>到期：<em class="text-primary">{{item.expirationTime}}</em></p>
                </div>
                <div class="app-item__footer">
                  <el-button-group>
                    <el-button @click="upgradeApp(item.id)" size="small">升级</el-button>
                    <el-button @click="renewApp(item.id)" size="small">续费</el-button>
                    <el-button @click="manageApp(item.appid,item.productCode)" size="small" type="primary">管理</el-button>
                  </el-button-group>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :total="totalSize"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import API from '@/api'
import { isPassword } from '@/utils/validate'
export default {
  data () {
    var validateComfirmPassword = (rule, value, callback) => {
        if (!isPassword(value)) {
          callback(new Error('6-12位的字母、数字'))
        }else if (this.passwordForm.newPassword !== value) {
          callback(new Error('确认密码与密码输入不一致'))
        } else {
          callback()
        }
      }
      var validateNewPassword = (rule, value, callback) => {
        if (!isPassword(value)) {
          callback(new Error('6-12位的字母、数字'))
        } else {
          callback()
        }
      }
    return {
      // 小程序列表表单
      appListForm: {
        selects: [],
        kind: '',
        keyword: ''
      },
      pageIndex: 1,
      pageSize: 10,
      totalSize: 0,
      dataListLoading: false,
      nameForm:{
        name:''
      },
      passwordForm:{
        oldPassword:'',
        newPassword:'',
        secNewPassword:''
      },
      nameFormVisible: false,
      passwordFormVisible: false,
      appList: [],
      nameFormRule: {
          name: [
            { required: true, message: '管理员名称不能为空', trigger: 'blur' }
          ]
      },
      passwordFormRule: {
          oldPassword: [
            { required: true, message: '旧密码不能为空', trigger: 'blur' }
          ],
          newPassword: [
            { required: true, message: '新密码不能为空', trigger: 'blur' },
            { validator: validateNewPassword, trigger: 'blur' }
          ],
          secNewPassword: [
            { required: true, message: '新密码不能为空', trigger: 'blur' }
            , { validator: validateComfirmPassword, trigger: 'blur' }
          ],
      }
    }
  },
  computed:{
    userId: {
      get () {
        return this.$store.state.user.id
      }
    },
    userName: {
      get () {
        return this.$store.state.user.name
      }
    },
    userMobile: {
      get () {
        return this.$store.state.user.mobile
      }
    },
    userType: {
      get () {
        return this.$store.state.user.userType
      }
    }
  },
  created () {
    this.getAppKind()
    this.getDataList()
  },
  methods: {
    // 获取小程序种类
    getAppKind () {
      API.miniapp.getMiniAppKind().then(({data}) => {
        if (data.code === 0) {
          this.appListForm.selects = data.items
        }
      })
    },
      // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 获取小程序列表信息
    getDataList () {
       this.dataListLoading = true
        var params = {
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
            't.productId_eq': this.appListForm.kind,
            't.name_like':this.appListForm.keyword
        }
        API.miniapp.getMiniAppList(params).then(({data}) => {
          if (data && data.code === 0) {
            this.appList = data.page.content
            this.totalSize = data.page.totalSize
            this.disabled = true
          } else {
            this.appList = []
            this.totalSize = 0
          }
          if(this.appList.length > 0){
            this.disabled = true
          } else {
            this.disabled = false
          }
          this.dataListLoading = false
        })
    },
    // 修改用户名
    updateUserName () {
      this.$refs['nameForm'].validate((valid) => {
        if (valid) {
          var params = {
            'name': this.nameForm.name,
          }
          API.miniapp.updateUserName(params).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
              })
              // todos，修改了用户名之后，如何更新。
              // this.$store.commit('user/updateName', window.localStorage.getItem('userName'))
              this.nameFormVisible = false;
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
      // 修改用户密码
    updatePassword () {
      this.$refs['passwordForm'].validate((valid) => {
        if (valid) {
          var params = {
            'password': this.passwordForm.oldPassword,
            'newPassword': this.passwordForm.newPassword
          }
          API.miniapp.updatePassword(params).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
              })
              this.passwordFormVisible = false;
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    // 登出
    loginOut () {
      API.common.logout().then(({data}) => {
        if (data.code === 0) {
          this.$cookie.delete('token')
          this.$router.replace({ name: 'login' })
        }
      }) // 登出处理
    },
    // 升级App
    upgradeApp (appId) {
    },
    // 续费App
    renewApp (appId) {
    },
    // 管理App
    manageApp (appId, type) {
      this.$router.push({ name: 'miniapp-' + type })
      this.$cookie.set('appid', appId)
      this.$cookie.set('apptype', type)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.logo{
  width: 210px;
  margin-right: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  color: #333;
  .logo__img{
    height: 32px;
    vertical-align: middle;
  }
  .logo__wrd{
    padding-left: 10px;
    vertical-align: middle;
  }
}
.app-list{
  .el-col{
    margin-bottom: 20px;
  }
}
.app-item{
  text-align: center;
  width: 100%;
  border: 1px solid #e3e3e3;
}
.app-item__header{
  line-height: 30px;
  padding: 10px;
  font-size: 18px;
  margin: 0;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  border-bottom: 1px solid #e3e3e3;
}
.app-item__content{
  padding: 10px 25px;
  font-size: 12px;
  text-align: left;
}
.app-item__content p{
  margin: 0;
  line-height: 24px;
}
.app-item__footer{
  padding: 10px;
  text-align: center;
  background-color: #f5f5f5;
  font-size: 12px;
  border-top: 1px solid #e3e3e3;
}
.main{
  min-height: 100%;
  width: 100%;
  background: #e7e8eb;
  min-width: 1180px;
  overflow: hidden;
}
.main-headerWrp{
    width: 100%;
    height: 62px;
    background-color: #FDFDFD;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .04);
}
.main-header{
  margin: 0 auto;
  width: 1100px;
  line-height: 62px;
}
.main-conwrp{
  margin: 20px auto;
  width: 1100px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #dedede;
  display: flex;
}
.main-side{
  padding: 16px 0;
  width: 250px;
}
.avatar{
  margin: 0 auto;
  width: 70px;
  height: 70px;
  position: relative;
}
.avatar__img{
  height: 70px;
  width: 70px;
  border-radius: 50%;
  display: block;
  overflow: hidden;
}
.avatar__editBg{
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  display: none;
  width: 100%;
  height: 100%;
  background-color: rgba(64, 64, 64, .75);
}
.avatar:hover{
  .avatar__editBg{
    display: block;
  }
}
.avatar__edit{
  cursor: pointer;
  height: 50px;
  width: 50px;
  line-height: 50px;
  margin: 10px;
  text-align: center;
  color: #fff;
  display: block;
  border-radius: 50%;
  &:hover{
    background-color: #38f;
  }
}
.user-namewrp{
  display: flex;
  margin: 20px auto;
  justify-content: center;
}
.user-name{
  display: block;
  max-width: 220px;
  line-height: 26px;
  background-color: #f1f4f7;
  border-radius: 10px;
  white-space: nowrap;
  overflow: hidden;
  padding: 0 10px;
  text-overflow: ellipsis;
}
.user-info__mod{
  padding: 0 10px;
  font-size: 16px;
  line-height: 17px;
  border-left: 4px solid #609ee9;
}
.user-info__item{
  line-height: 24px;
  margin-top: 10px;
  padding: 0 15px;
  font-size: 13px;
}
.user-info__btn{
  padding: 0 7px;
  border-radius: 5px;
  background-color: #d5efff;
}
.main-content{
  border-left: 1px solid #dedede;
  padding: 16px 26px;
  width: 850px;
}
.hLink{
  display: inline-block;
  text-align: center;
  width: 130px;
  height: 62px;
  font-size: 16px;
  cursor: pointer;
}
.hLink--active{
  @extend .hLink;
  color: #38adff;
  border-bottom: 3px solid #38adff;
}
</style>
